/**
 * 
 */
package com.mobile2you.nci.android.utils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.mobile2you.nci.android.R;
import com.mobile2you.nci.android.domain.Centres;

/**
 * @author JBromo
 * 
 */
public class Utils {

	public static Location userLocation;

	public static Centres centreSelected;

	public static List<Centres> addDistance(List<Centres> list,
			Location location) {
		try {
			List<Centres> result = new ArrayList<Centres>();
			for (Centres centres : list) {
				double latitude = centres.getLatitude();
				double longitude = centres.getLongitude();
				float[] results = new float[3];
				Location.distanceBetween(location.getLatitude(),
						location.getLongitude(), latitude, longitude, results);
				centres.setDistance(results[0]);
				result.add(centres);

			}
			return result;
		} catch (Exception e) {
			return list;
		}

	}

	public synchronized static void addmarkerCustom(Context context,
			List<Centres> ticket, MapView myMapView,
			BulleDialog.onBullClickListener listener) {
		List<Overlay> mapOverlays = myMapView.getOverlays();
		Collections.synchronizedList(mapOverlays);
		Drawable myPlace = context.getResources().getDrawable(
				R.drawable.position);
		MarkerTicket iconMyPlace = new MarkerTicket(myPlace, context,
				myMapView, listener);
		for (Centres ticketitem : ticket) {
			GeoPoint point = new GeoPoint(
					(int) (ticketitem.getLatitude() * 1E6),
					(int) (ticketitem.getLongitude() * 1E6));
			OverlayItem itemposition = new OverlayItem(point, "Ma positon",
					"Ma Distance :");
			iconMyPlace.addOverlay(itemposition, ticketitem);
		}
		MyLocationOverlay myLocationOverlay = new MyLocationOverlay(context,
				myMapView);
		myLocationOverlay.enableMyLocation();
		mapOverlays.add(myLocationOverlay);

		mapOverlays.add(iconMyPlace);
	}

	public synchronized static boolean drawItineraire(Document doc,
			MapView mMapView01) {

		if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) {

			String path = doc.getElementsByTagName("GeometryCollection")
					.item(0).getFirstChild().getFirstChild().getFirstChild()
					.getNodeValue();

			String[] pairs = path.split(" ");
			String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude
			// lngLat[1]=latitude
			// lngLat[2]=height

			GeoPoint startGP = new GeoPoint(
					(int) (Double.parseDouble(lngLat[1]) * 1E6),
					(int) (Double.parseDouble(lngLat[0]) * 1E6));
			Collections.synchronizedList(mMapView01.getOverlays()).add(
					new DrawRoute(startGP, startGP, 1));
			GeoPoint gp1;
			GeoPoint gp2 = startGP;

			for (int i = 1; i < pairs.length; i++) {
				lngLat = pairs[i].split(",");
				gp1 = gp2;

				gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6),
						(int) (Double.parseDouble(lngLat[0]) * 1E6));
				Collections.synchronizedList(mMapView01.getOverlays()).add(
						new DrawRoute(gp1, gp2, 2, Color.BLUE));

			}

		}
		return true;

	}

	public synchronized static void drawItineraireThread(final Centres point,
			final Location location, final Handler receiver) {
		new Thread() {
			@Override
			public void run() {
				try {
					Document document = Utils.loadItineraire(point, location);
					Message msg = Message.obtain();
					if (document == null) {
						msg.arg1 = 0;
					} else {
						msg.arg1 = 1;
						msg.obj = document;

					}
					receiver.sendMessage(msg);
				} catch (Exception e) {
					Message msg = Message.obtain();
					msg.arg1 = 0;
					receiver.sendMessage(msg);
				}
			}

		}.start();
	}

	/**
	 * 
	 * @return agence distance as format String
	 */
	public static String getDistanceAsString(double distance) {
		DecimalFormat df = new DecimalFormat("#.##");
		String dis = "";
		if (distance < 1000) {
			dis = (int) distance + "m";
		} else {
			double d = distance / 1000;
			dis = df.format(d) + " km";
		}
		return dis;
	}

	public static String getEncrytedPassword(String param) {
		String result = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] digest = md5.digest(param.getBytes());
			result = toHex(digest);
		} catch (Exception e) {

			e.printStackTrace();
		}
		return result.toLowerCase();
	}

	public static void lanceCall(Context context, String num) {
		Intent senderIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
				+ num));
		senderIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(senderIntent);

	}

	public static void lancerActiviter(Context context,
			Class<? extends Activity> activityClass) {
		Intent i = new Intent(context, activityClass);
		context.startActivity(i);

	}

	public static Document loadItineraire(Centres ticketitem,
			Location userLocation) {

		float result[] = new float[3];
		Location.distanceBetween(userLocation.getLatitude(),
				userLocation.getLongitude(), ticketitem.getLatitude(),
				ticketitem.getLongitude(), result);
		float distance = result[0];
		GeoPoint point = new GeoPoint((int) (ticketitem.getLatitude() * 1E6),
				(int) (ticketitem.getLongitude() * 1E6));
		if (distance < 5000) {
			return loadItineraire(point, true);
		}
		if (distance >= 5000 && distance < 50 * 1000) {
			return loadItineraire(point, false);
		}
		return null;

	}

	public static Document loadItineraire(GeoPoint agencePosition,
			boolean walking) {
		Document doc = null;
		if (Utils.userLocation != null) {

			StringBuilder urlString = new StringBuilder();
			GeoPoint userPosition = new GeoPoint(
					(int) (Utils.userLocation.getLatitude() * 1E6),
					(int) (Utils.userLocation.getLongitude() * 1E6));
			urlString.append("http://maps.google.com/maps?f=d&hl=en");
			urlString.append("&saddr=");// from
			urlString
					.append(Double.toString(userPosition.getLatitudeE6() / 1.0E6));
			urlString.append(",");
			urlString
					.append(Double.toString(userPosition.getLongitudeE6() / 1.0E6));
			urlString.append("&daddr=");// to
			urlString
					.append(Double.toString(agencePosition.getLatitudeE6() / 1.0E6));
			urlString.append(",");
			if (walking) {
				urlString.append(Double.toString(agencePosition
						.getLongitudeE6() / 1.0E6));
				urlString.append("&ie=UTF8&0&om=0&output=kml&dirflg=w");

			} else {
				urlString.append(Double.toString(agencePosition
						.getLongitudeE6() / 1.0E6));
				urlString.append("&ie=UTF8&0&om=0&output=kml");
			}

			HttpURLConnection urlConnection = null;
			URL url = null;
			try {
				// Open connexion
				url = new URL(urlString.toString());
				urlConnection = (HttpURLConnection) url.openConnection();
				urlConnection.setRequestMethod("GET");
				urlConnection.setDoOutput(true);
				urlConnection.setDoInput(true);
				urlConnection.connect();
				// Parse DOM response
				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				doc = db.parse(urlConnection.getInputStream());
			} catch (Exception exception) {
			}
		}
		return doc;

	}

	private static String toHex(byte[] a) {
		StringBuilder sb = new StringBuilder(a.length * 2);
		for (int i = 0; i < a.length; i++) {
			sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
			sb.append(Character.forDigit(a[i] & 0x0f, 16));
		}
		return sb.toString();
	}

	public static void zoomInBounds(final MapView view,
			final List<Centres> listTicket) {
		try {

			int minLat = Integer.MAX_VALUE;
			int minLong = Integer.MAX_VALUE;
			int maxLat = Integer.MIN_VALUE;
			int maxLong = Integer.MIN_VALUE;

			for (Centres ticket : listTicket) {
				GeoPoint point = new GeoPoint(
						(int) (ticket.getLatitude() * 1E6),
						(int) (ticket.getLongitude() * 1E6));
				minLat = Math.min(point.getLatitudeE6(), minLat);
				minLong = Math.min(point.getLongitudeE6(), minLong);
				maxLat = Math.max(point.getLatitudeE6(), maxLat);
				maxLong = Math.max(point.getLongitudeE6(), maxLong);
			}
			if (Utils.userLocation != null) {
				GeoPoint pointUser = new GeoPoint(
						(int) (Utils.userLocation.getLatitude() * 1E6),
						(int) (Utils.userLocation.getLongitude() * 1E6));

				minLat = Math.min(pointUser.getLatitudeE6(), minLat);
				minLong = Math.min(pointUser.getLongitudeE6(), minLong);
				maxLat = Math.max(pointUser.getLatitudeE6(), maxLat);
				maxLong = Math.max(pointUser.getLongitudeE6(), maxLong);
			}

			final MapController controller = view.getController();
			controller.zoomToSpan(Math.abs(minLat - maxLat),
					Math.abs(minLong - maxLong));
			controller.animateTo(new GeoPoint((maxLat + minLat) / 2,
					(maxLong + minLong) / 2));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
